import threading
from tkinter import Label, Button, Entry

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.comm.msg_util import msg


class WinModel():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.label = Label(tab, text="输入：")
        self.label.pack()

        self.entry = Entry(self.tab)
        self.entry.pack()

        self.button = Button(self.tab, text="输出", command=self.print_entry_sync)
        self.button.pack()

    def print_entry_sync(self):
        if hasattr(self, 'sync_flag') and self.sync_flag == '1':
            msg('正在处理,请勿重复操作')
            return
        self.sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=()), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.sync_flag = '0'

    def print_entry(self):
        if hasattr(self, 'label_out'):
            self.label_out.destroy()
        self.label_out = Label(self.tab, text="结果：%s" % self.entry.get())
        self.label_out.pack()



